(function(){
  'use strict';

  if (!window.Api) return;
  
  // 获取交易所显示信息（使用真实logo）
  function getExchangeDisplayInfo(connector) {
    var exchangeMap = {
      'binance': { logo: 'binance.png', cn: '币安现货', en: 'Binance' },
      'binance_us': { logo: 'binance.png', cn: '币安美国现货', en: 'Binance US' },
      'binance_perpetual': { logo: 'binance.png', cn: '币安合约', en: 'Binance Perpetual' },
      'gate': { logo: 'gateio.png', cn: '芝麻开门现货', en: 'Gate.io' },
      'gate_io': { logo: 'gateio.png', cn: '芝麻开门现货', en: 'Gate.io' },
      'gate_io_perpetual': { logo: 'gateio.png', cn: '芝麻开门合约', en: 'Gate.io Perpetual' },
      'okx': { logo: 'okx.png', cn: '欧易现货', en: 'OKX' },
      'okx_perpetual': { logo: 'okx.png', cn: '欧易合约', en: 'OKX Perpetual' },
      'huobi': { logo: 'huobi.png', cn: '火币现货', en: 'Huobi' },
      'htx': { logo: 'huobi.png', cn: '火币HTX现货', en: 'HTX' },
      'huobi_perpetual': { logo: 'huobi.png', cn: '火币合约', en: 'Huobi Perpetual' },
      'kraken': { logo: 'kraken.png', cn: '海妖现货', en: 'Kraken' },
      'kraken_perpetual': { logo: 'kraken.png', cn: '海妖合约', en: 'Kraken Perpetual' },
      'coinbase': { logo: 'coinbase.png', cn: 'Coinbase现货', en: 'Coinbase' },
      'coinbase_perpetual': { logo: 'coinbase.png', cn: 'Coinbase合约', en: 'Coinbase Perpetual' },
      'kucoin': { logo: 'kucoin.png', cn: '库币现货', en: 'KuCoin' },
      'kucoin_perpetual': { logo: 'kucoin.png', cn: '库币合约', en: 'KuCoin Perpetual' },
      'mexc': { logo: 'mexc.png', cn: '抹茶现货', en: 'MEXC' },
      'bingx': { logo: 'bingx.png', cn: '必应现货', en: 'BingX' },
      'bing_x': { logo: 'bingx.png', cn: '必应现货', en: 'BingX' },
      'bitmart': { logo: 'bitmart.png', cn: '比特玛特现货', en: 'BitMart' },
      'bitrue': { logo: 'bitrue.png', cn: '比特真现货', en: 'Bitrue' },
      'bitstamp': { logo: 'bitstamp.png', cn: 'Bitstamp现货', en: 'Bitstamp' },
      'vertex': { logo: 'vertex-protocol.png', cn: 'Vertex现货', en: 'Vertex' },
      'injective': { logo: 'injective.png', cn: 'Injective现货', en: 'Injective' },
      'injective_v2': { logo: 'injective.png', cn: 'Injective V2现货', en: 'Injective V2' },
      'ndax': { logo: 'ndax.png', cn: 'NDAX现货', en: 'NDAX' },
      'bybit': { logo: 'bybit.png', cn: 'Bybit现货', en: 'Bybit' },
      'bybit_perpetual': { logo: 'bybit.png', cn: 'Bybit合约', en: 'Bybit Perpetual' },
      'kucoin_hft': { logo: 'kucoin.png', cn: '库币HFT现货', en: 'KuCoin HFT' },
      'bitget': { logo: 'bitget.png', cn: 'Bitget现货', en: 'Bitget' },
      'crypto_com': { logo: 'crypto-dot-com.png', cn: 'Crypto.com现货', en: 'Crypto.com' },
      'ascend_ex': { logo: 'ascendex.png', cn: 'AscendEX现货', en: 'AscendEX' },
      'ascendex': { logo: 'ascendex.png', cn: 'AscendEX现货', en: 'AscendEX' },
      'btc_markets': { logo: 'btcmarkets.png', cn: 'BTC Markets现货', en: 'BTC Markets' },
      'cube': { logo: 'ascendex.png', cn: 'Cube现货', en: 'Cube' },
      'hyperliquid': { logo: 'hyperliquid.png', cn: 'Hyperliquid现货', en: 'Hyperliquid' }
    };
    
    var exchange = exchangeMap[connector];
    if (exchange) {
      return {
        logo: exchange.logo,
        name: exchange.cn + ' (' + exchange.en + ')'
      };
    }
    
    return { logo: 'binance.png', name: connector };
  }

  var emailEl = document.getElementById('authed-email');
  var listAccounts = document.getElementById('list-accounts');
  var boundConnectorsWrap = document.getElementById('bound-connectors-list');
  var refreshBtn = document.getElementById('btn-refresh-connectors');
  var setTvEnabled = document.getElementById('set-tv-enabled');
  var setGlobalPause = document.getElementById('set-global-pause');
  var bindAccountInput = document.getElementById('bind-account');

  async function load(){
    if (window.Auth && typeof window.Auth.updateAuthView === 'function') window.Auth.updateAuthView();

    // 检查登录状态
    var token = window.Auth && window.Auth.getToken ? window.Auth.getToken() : '';
    console.log('当前token状态:', { hasToken: !!token, tokenLength: token ? token.length : 0 });

    // me
    try {
      var me = await window.Api.jsonOrThrow(await window.Api.request('GET','/auth/me',null,true));
      console.log('用户信息获取成功:', me);
      
      // 检查是否为管理员
      var isAdmin = !!(me && (me.role === 'admin' || me.is_admin));
      console.log('用户权限检查:', { isAdmin: isAdmin, userInfo: me });
      
      // 如果是管理员，直接跳转到admin.html
      if (isAdmin) {
        console.log('检测到管理员账号，跳转到admin.html...');
        window.location.href = 'admin.html';
        return;
      }
      
      // 根据用户权限显示或隐藏管理员界面选项
      var adminEntry = document.getElementById('admin-strategy-mgr-entry');
      if (adminEntry) {
        adminEntry.style.display = 'none';
        console.log('隐藏管理员界面选项（普通用户）');
      }
      
      if (emailEl) emailEl.textContent = me && me.email ? me.email : '已登录';
      if (setTvEnabled) setTvEnabled.checked = !!(me && me.tv_enabled);
      if (setGlobalPause) setGlobalPause.checked = !!(me && me.global_pause);
      if (bindAccountInput) bindAccountInput.value = me && me.email ? me.email : '';
    } catch (err) {
      if (err && err.message && err.message.indexOf('401') >= 0 && window.Auth && window.Auth.logout) {
        window.Auth.logout();
        window.Auth.updateAuthView && window.Auth.updateAuthView();
      }
    }


    // accounts / bound connectors
    try {
      console.log('开始加载账户信息...');
      var accountsResp = await window.Api.jsonOrThrow(await window.Api.request('GET','/users/accounts',null,true));
      console.log('账户信息API响应:', accountsResp);
      var accountItems = Array.isArray(accountsResp) ? accountsResp : (accountsResp && accountsResp.items) || [];
      console.log('处理后的账户数据:', accountItems);
      console.log('第一个账户的字段:', accountItems.length > 0 ? Object.keys(accountItems[0]) : '无账户数据');
      renderAccounts(accountItems);

      console.log('开始加载连接器信息...');
      var connectorsResp = await window.Api.request('GET','/users/connectors',null,true);
      console.log('连接器API响应状态:', connectorsResp.status, connectorsResp.ok);
      if (connectorsResp.ok){
        var connectorsJson = await connectorsResp.json().catch(function(err){ console.log('解析连接器JSON失败:', err); return {};});
        console.log('连接器数据:', connectorsJson);
        var connectorList = connectorsJson.connectors || connectorsJson || [];
        
        // 检查是否有绑定的连接器
        if (Array.isArray(connectorList) && connectorList.length > 0) {
          console.log('发现已绑定的连接器:', connectorList);
          // 如果有绑定的连接器，直接显示它们
          renderBoundConnectorsFromConnectors(connectorList);
        } else {
          console.log('没有绑定的连接器，使用账户数据');
          renderBoundConnectors(accountItems, connectorList);
        }
      } else {
        console.log('连接器API调用失败，状态码:', connectorsResp.status);
        renderBoundConnectors(accountItems, []);
      }
    } catch (err) {
      console.log('加载账户/连接器信息失败:', err);
      if (listAccounts) listAccounts.innerHTML = '<li class="muted">加载失败</li>';
      if (boundConnectorsWrap) boundConnectorsWrap.innerHTML = '<p class="muted">加载失败</p>';
    }
  }

  function renderAccounts(accounts){
    if (!listAccounts) return;
    listAccounts.innerHTML='';
    if (!Array.isArray(accounts) || !accounts.length){ listAccounts.innerHTML='<li class="muted">未检测到交易账户</li>'; return; }
    var grouped={};
    accounts.forEach(function(a){ var name=a.account_name||a.name||''; if(!name) return; if(!grouped[name]) grouped[name]=[]; if(a.connector) grouped[name].push(a); });
    var names=Object.keys(grouped); if(!names.length){ names=[accounts[0].account_name||accounts[0].name||'账户']; grouped[names[0]]=[]; }
    names.forEach(function(name){
      var connectors=grouped[name]||[]; var li=document.createElement('li');
      if (!connectors.length) li.textContent='账户：'+name+' · 尚未绑定交易所';
      else {
        var parts=connectors.map(function(c){ return (c.connector||'未知') + (c.status ? '（'+c.status+'）' : ''); });
        li.textContent='账户：'+name+' · 交易所：'+parts.join('、');
      }
      listAccounts.appendChild(li);
    });
  }

  function renderBoundConnectorsFromConnectors(connectors){
    if (!boundConnectorsWrap) return;
    boundConnectorsWrap.innerHTML='';
    console.log('从连接器API渲染绑定状态:', connectors);
    
    if (!Array.isArray(connectors) || !connectors.length) {
      boundConnectorsWrap.innerHTML='<p class="muted">暂无绑定记录，请使用下方"选择连接器"功能绑定交易所</p>';
      return;
    }
    
    connectors.forEach(function(conn){
      var div=document.createElement('div'); 
      div.className='bound-connector-item'; 
      div.style.padding='6px 0';
      div.style.display='flex';
      div.style.alignItems='center';
      div.style.gap='8px';
      
      // 获取交易所显示信息
      var exchangeInfo = getExchangeDisplayInfo(conn);
      
      // 创建图标
      var icon = document.createElement('img');
      icon.src = 'assets/icons/exchanges/' + exchangeInfo.logo;
      icon.alt = exchangeInfo.name;
      icon.style.width = '16px';
      icon.style.height = '16px';
      icon.style.objectFit = 'contain';
      icon.style.borderRadius = '2px';
      
      // 创建名称
      var name = document.createElement('span');
      name.textContent = exchangeInfo.name + ' · 已绑定账户';
      
      div.appendChild(icon);
      div.appendChild(name);
      boundConnectorsWrap.appendChild(div);
      console.log('添加已绑定连接器项:', exchangeInfo.name);
    });
  }

  function renderBoundConnectors(accounts, connectors){
    if (!boundConnectorsWrap) return;
    boundConnectorsWrap.innerHTML='';
    console.log('渲染绑定连接器:', { accounts: accounts, connectors: connectors });
    
    var map={};
    (Array.isArray(accounts)?accounts:[]).forEach(function(a){ 
      console.log('处理账户:', a);
      // 尝试多种可能的字段名
      var conn = a.connector || a.connector_name || a.exchange || a.exchange_name;
      var accountName = a.account_name || a.name || a.account || a.email;
      console.log('提取的连接器:', conn, '账户名:', accountName);
      
      if(!conn) {
        console.log('跳过账户，无连接器信息:', a);
        return; 
      } 
      if(!map[conn]) map[conn]=[]; 
      map[conn].push(accountName || ''); 
    });
    console.log('账户映射:', map);
    
    var connectorList = Array.isArray(connectors)?connectors:[];
    console.log('连接器列表:', connectorList);
    
    if (!connectorList.length && Object.keys(map).length===0){ 
      boundConnectorsWrap.innerHTML='<p class="muted">暂无绑定记录</p>'; 
      return; 
    }
    connectorList.sort();
    connectorList.forEach(function(conn){
      var accountsForConn = map[conn] || [];
      var div=document.createElement('div'); 
      div.className='bound-connector-item'; 
      div.style.padding='6px 0';
      var label = conn + (accountsForConn.length ? (' · 账户：' + accountsForConn.join('、')) : ' · 尚未绑定账户');
      div.textContent = label;
      boundConnectorsWrap.appendChild(div);
      console.log('添加连接器项:', label);
    });
  }

  if (refreshBtn) refreshBtn.addEventListener('click', function(){ load(); });

  load();
  window.loadSettingsData = load;
  if (window.Auth) window.Auth.loadData = load;
})();


